<?php
/**
 * Created by PhpStorm.
 * User: liuchaozhong
 * Date: 2018/8/22
 * Time: 下午5:59
 */
namespace App\Models;

use Faker\Provider\Base;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class TaskConfigLog extends Model
{
    protected $table = 'task_config_log';
    public $timestamps = false;
    public $fillable = ['member_id','task_id','date','nums'];

    //添加当天任务记录
    public function addConfigLog($member_id, $task_id)
    {
        $today = date('Y-m-d');
        $info = TaskConfigLog::where('member_id',$member_id)
            ->where('task_id', $task_id)
            ->where('date',$today)
            ->first();
        if(!empty($info)) {
            $info->nums = $info->nums + 1;
            $res = $info->save();
        }else {
            $insert = [
                'member_id' => $member_id,
                'task_id' => $task_id,
                'date' => $today,
                'nums' => 1
            ];
            $res = TaskConfigLog::create($insert);
        }
        if($res) {
            $this->isFinishTask($member_id, $task_id);
        }

        return $res ? $res : false;
    }

    //判断是否满足任务要去进行积分货金币增加操作
    protected function isFinishTask($member_id, $task_id)
    {
        switch ($task_id) {
            //邀请好友
            case 2:
                $invite_list = InviteLog::with(['g_bmember'=>function($query){
                    return $query->select('id','name');
                }])
                    ->where('invite_id', $member_id)
                    ->where('it_date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                //增加好友数量
                $member_info->child_nums = $member_info->child_nums + 1;
                $member_info->save();
                $this->inviteHandle($member_info, $invite_list, $task_id);
                break;
            //签到分享
            case 3:
                $share_checkin_list = ShareCheckIn::where('member_id', $member_id)
                    ->where('date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                $this->shareCheckinHandle($member_info, $share_checkin_list, $task_id);
                break;
            //分享好友观看
            case 4:
                $share_list = ShareLog::where('member_id', $member_id)
                    ->where('types', 2)
                    ->where('date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                $this->shareHandle($member_info, $share_list, $task_id, 2);
                break;
            //首次观看视频
            case 5:
                $view_list = ViewLog::with(['g_article'=>function($query){
                    return $query->select('id','title');
                }])
                    ->where('member_id', $member_id)
                    ->orderby('id','asc')
                    ->take(1)
                    ->get();
                $member_info = Member::find($member_id);
                $this->firstViewHandle($member_info, $view_list, $task_id);
                break;
            //观看十个视频任务
            case 6:
                $view_list = ViewLog::with(['g_article'=>function($query){
                    return $query->select('id','title');
                }])
                    ->where('member_id', $member_id)
                    ->where('date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                $this->viewHandle($member_info, $view_list, $task_id);
                break;
            //首个分享视频
            case 10:
                $share_list = ShareLog::with(['g_article'=>function($query){
                    return $query->select('id','title');
                }])
                    ->where('member_id', $member_id)
                    ->where('types', 0)
                    ->orderby('id','asc')
                    ->take(1)
                    ->get();
                $member_info = Member::find($member_id);
                $this->firstShareHandle($member_info, $share_list, $task_id);
                break;
            //分享5个视频任务
            case 7:
                $share_list = ShareLog::with(['g_article'=>function($query){
                    return $query->select('id','title');
                }])
                    ->where('member_id', $member_id)
                    ->where('types', 0)
                    ->where('date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                $this->shareHandle($member_info, $share_list, $task_id);
                break;
            //首次推荐小程序
            case 8:
                $share_list = ShareLog::where('member_id', $member_id)
                    ->where('types', 1)
                    ->orderby('id','asc')
                    ->take(1)
                    ->get();
                $member_info = Member::find($member_id);
                $this->firstShareHandle($member_info, $share_list, $task_id, 1);
                break;
            //推荐5次小程序
            case 9:
                $share_list = ShareLog::where('member_id', $member_id)
                    ->where('types', 1)
                    ->where('date', date('Y-m-d'))
                    ->get();
                $member_info = Member::find($member_id);
                $this->shareHandle($member_info, $share_list, $task_id, 1);
                break;
        }
    }

    /**
     * 处理观看任务
     * @param $member_info 用户信息
     * @param $view_list   当天观看记录
     * @param $task_id     任务id
     */
    protected function viewHandle($member_info, $view_list, $task_id)
    {
        $total = count($view_list);
        $no = $total-1;
        $dd = $view_list->toArray();
        $last_view = array_pop($dd);
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money);
        }
        if($money > 0 && $total<=$len) {
            $member_info->bi = $member_info->bi + $money;
            $member_info->save();
            //写入资金记录
            $capital_insert = [
                'type_id' => $task_id,
                'member_id' => $member_info->id,
                'money' => $money,
                'bei' => sprintf('今日第%s次浏览[%s],奖励[%s]金币', $total, $last_view['g_article']['title'], $money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    //处理分享签到
    protected function shareCheckinHandle($member_info, $invite_list, $task_id)
    {
        $total = count($invite_list);
        $no = $total-1;
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money);
        }
        if($money > 0 && $total<=$len) {
            $member_info->bi = $member_info->bi + $money;
            $member_info->save();
            //写入资金记录
            $capital_insert = [
                'type_id' => $task_id,
                'member_id' => $member_info->id,
                'money' => $money,
                'bei' => sprintf('今日第%s次分享签到,奖励[%s]金币',$total, $money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    //处理邀请好友
    protected function inviteHandle($member_info, $invite_list, $task_id)
    {
        $total = count($invite_list);
        $no = $total-1;
        $dd = $invite_list->toArray();
        $last_view = array_pop($dd);
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money, 1);
        }
        if($money > 0 && $total<=$len) {
            $member_info->account = $member_info->account + $money;
            $member_info->save();
            //写入资金记录
            $capital_insert = [
                'type_id' => $task_id,
                'member_id' => $member_info->id,
                'money_cash' => $money,
                'bei' => sprintf('今日第%s次邀请好友[%s],奖励[%s]元',$total, $last_view['g_bmember']['name'], $money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    //处理首次观看视频
    protected function firstViewHandle($member_info, $view_list, $task_id)
    {
        $total = count($view_list);
        $no = $total-1;
        $dd = $view_list->toArray();
        $last_view = array_pop($dd);
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money);
        }
        if($money > 0 && $total<=$len) {
            $member_info->bi = $member_info->bi + $money;
            $member_info->save();
            //写入资金记录
            $capital_insert = [
                'type_id' => $task_id,
                'member_id' => $member_info->id,
                'money' => $money,
                'bei' => sprintf('首次浏览[%s],奖励[%s]金币', $last_view['g_article']['title'], $money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    //处理首次分享
    protected function firstShareHandle($member_info, $share_list, $task_id, $type=0)
    {
        $total = count($share_list);
        $no = $total-1;
        $dd = $share_list->toArray();
        $last_view = array_pop($dd);
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money);
        }
        if($money > 0 && $total<=$len) {
            $member_info->bi = $member_info->bi + $money;
            $member_info->save();
            //写入资金记录
            if($type) {
                $capital_insert = [
                    'type_id' => $task_id,
                    'member_id' => $member_info->id,
                    'money' => $money,
                    'bei' => sprintf('首次推荐小程序,奖励[%s]金币', $money),
                    'from_source' => getIp(),
                    'date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }else{
                $capital_insert = [
                    'type_id' => $task_id,
                    'member_id' => $member_info->id,
                    'money' => $money,
                    'bei' => sprintf('首次分享[%s],奖励[%s]金币', $last_view['g_article']['title'], $money),
                    'from_source' => getIp(),
                    'date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    //处理分享视频
    protected function shareHandle($member_info, $share_list, $task_id, $type=0)
    {
        $total = count($share_list);
        $no = $total-1;
        $dd = $share_list->toArray();
        $last_view = array_pop($dd);
        $check_task = TaskConfig::where('id', $task_id)->first(); //获取任务
        $task_config = unserialize($check_task['config']);
        try{
            preg_match('/\d+/',$task_config['td'][$no], $money);  //数额
            $money = $money[0];
        }catch (\Exception $e) {
            $money = 0;
        }
        $len = count($task_config['td']);
        //判断是否有上级
        if($member_info->pid > 0 && $money>0) {
            $this->parentSy($member_info, $member_info->pid, $money);
        }
        if($money > 0 && $total<=$len) {
            $member_info->bi = $member_info->bi + $money;
            $member_info->save();
            if($type == 1) {
                $capital_insert = [
                    'type_id' => $task_id,
                    'member_id' => $member_info->id,
                    'money' => $money,
                    'bei' => sprintf('今日第%s次推荐小程序,奖励[%s]金币', $total, $money),
                    'from_source' => getIp(),
                    'date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }else if($type == 2){
                $capital_insert = [
                    'type_id' => $task_id,
                    'member_id' => $member_info->id,
                    'money' => $money,
                    'bei' => sprintf('今日第%s次分享好友观看,奖励[%s]金币', $total, $money),
                    'from_source' => getIp(),
                    'date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            } else{
                //写入资金记录
                $capital_insert = [
                    'type_id' => $task_id,
                    'member_id' => $member_info->id,
                    'money' => $money,
                    'bei' => sprintf('今日第%s次分享[%s],奖励[%s]金币', $total, $last_view['g_article']['title'], $money),
                    'from_source' => getIp(),
                    'date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
            DB::table('capital_log')->insert($capital_insert);
        }
    }

    /**
     * 处理上级获取奖励
     * @param $member_info 用户信息
     * @param $pid 父级id
     * @param $money 得到的奖励
     * @param $type 得到的奖励类型 0金币 1现金
     */
    protected function parentSy($member_info, $pid, $money, $type=0)
    {
        $p_member_info = Member::find($pid);
        $config = Basic::where('keyword', 'pbl')->first();
        preg_match('/\d+/', $config->val, $bi);
        $bi = $bi[0];
        $p_money = $money * $bi /100;
        if($type){
            $p_member_info->account = $p_member_info->account + $p_money;
            //写入资金记录
            $capital_insert = [
                'type_id' => 0,
                'member_id' => $pid,
                'money_cash' => $p_money,
                'bei' => sprintf('通过下级%s,获取奖励[%s]元', $member_info->name, $p_money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
        }else {
            $p_member_info->bi = $p_member_info->bi + $p_money;
            //写入资金记录
            $capital_insert = [
                'type_id' => 0,
                'member_id' => $pid,
                'money' => $p_money,
                'bei' => sprintf('通过下级%s,获取奖励[%s]金币', $member_info->name, $p_money),
                'from_source' => getIp(),
                'date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
        }
        $p_member_info->save();
        DB::table('capital_log')->insert($capital_insert);
    }

    //视频弹框
    public function getalertConfig($member_id)
    {
        $view_where = [
            'member_id' => $member_id,
            'date' => date('Y-m-d'),
        ];
        $share_where = $view_where;
        $share_where['task_id'] = 7;
        $share_all = TaskConfigLog::select('nums')->where($share_where)->first();
        $view_where['task_id'] = 6;
        $view_all = TaskConfigLog::select('nums')->where($view_where)->first();
        $task_config = TaskConfig::select('config')
            ->whereIn('id', [5, 6, 7, 10])
            ->get()
            ->toArray();
        for($i=0;$i<count($task_config);$i++){
            $temp[$i] = unserialize($task_config[$i]['config']);
        }
        $view_all['nums'] = isset($view_all['nums']) ? $view_all['nums'] : 0;
        $share_all['nums'] = isset($share_all['nums']) ? $share_all['nums'] : 0;
        $finish_money['view_finish'] = $view_all['nums'];
        $finish_money['view_total'] = count($temp[1]['th']);
        $finish_money['share_finish'] = $share_all['nums'];
        $finish_money['share_total'] = count($temp[2]['th']);
        if($view_all['nums'] < 1) {
            $finish_money['view_finish_money'] = (int)$temp[0]['td'][$view_all['nums']] + (int)$temp[1]['td'][$view_all['nums']];
        }else if($view_all['nums'] < count($temp[1]['th'])) {
            $finish_money['view_finish_money'] = (int)$temp[1]['td'][$view_all['nums']];
        }else{
            $finish_money['view_finish_money'] = 0;
        }
        if($share_all['nums'] < 1) {
            $finish_money['share_finish_money'] = (int)$temp[3]['td'][$share_all['nums']] + (int)$temp[2]['td'][$share_all['nums']];
        }else if($share_all['nums'] < count($temp[2]['th'])) {
            $finish_money['share_finish_money'] = (int)$temp[2]['td'][$share_all['nums']];
        }else{
            $finish_money['share_finish_money'] = 0;
        }
        return $finish_money;
    }
}